﻿using System;
using nRoute.Components;
using nRoute.Components.Composition;
using nRoute.Utilities;

namespace nRoute.Mapping
{
    public class DefaultModulesLocator
         : ResourceLocator, IIntializableResource
    {
        private readonly string _moduleName;
        private readonly InitializationMode _initializationMode;

        public DefaultModulesLocator(string moduleName, Type moduleType, InitializationMode initializationMode)
            : base(typeof(IModule), moduleType, new SingletonLifetimeManager())
        {
            Guard.ArgumentNotNull(moduleType, "moduleType");

            _moduleName = moduleName;
            _initializationMode = initializationMode;
        }

#region Properties

        public string ModuleName
        {
            get { return _moduleName; } 
        }

        public InitializationMode InitializationMode
        {
            get { return _initializationMode; }
        }

#endregion

#region IIntializableResource

        bool IIntializableResource.CanInitialize(ITypeBuilder typeBuilder)
        {
            return true;
        }

        void IIntializableResource.Initialize(ITypeBuilder typeBuilder)
        {
            if (_initializationMode == InitializationMode.WhenAvailable)
            {
                base.GetInstance(typeBuilder);
            }
        }

        protected override object CreateResourceInstance(ITypeBuilder typeBuilder)
        {
            var _resource = (IModule)base.CreateResourceInstance(typeBuilder);
            if (_resource != null) _resource.Initialize();
            return _resource;
        }

#endregion

    }
}
